package dnablockfinder;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class EvoBranch extends EvoNode {
	private EvoNode leftChild;
	private EvoNode rightChild;
	private Analysis[] analysis;

	@Override
	protected int parseInternal(String parseString, int index,
			char endTag, Map<String,String> sequences) {
		index ++;
		leftChild = factory(parseString, index);
		index = leftChild.parse(parseString, index, ',', sequences) + 1;
		rightChild = factory(parseString, index);
		return rightChild.parse(parseString, index, ')', sequences) + 1;
	}

	@Override
	public Analysis[] analyze(int filterRadius) {
		Analysis[] leftData = leftChild.analyze(filterRadius);
		Analysis[] rightData = rightChild.analyze(filterRadius);
		analysis = new Analysis[leftData.length];
		for (int i = 0; i < analysis.length; i ++)
			analysis[i] = new Analysis(i == 0 ? null : analysis[i - 1],
				leftData[i], leftChild.evoLength,
				rightData[i], rightChild.evoLength);
		for (int i = 0; i < analysis.length; i ++)
			if (! analysis[i].shouldIgnore())
				analysis[i].filter(filterRadius, leftData[i], rightData[i]);
		return analysis;
	}

	@Override
	public String print(Path path) throws IOException {
		List<String> printOut = new ArrayList<>();
		for (int mdInd = 0; mdInd < analysis.length; mdInd ++) {
			String outStr = analysis[mdInd].print();
			if (outStr.length() != 0)
				printOut.add((mdInd + 1) + "," + outStr);
		}

		String leftStrand = leftChild.print(path);
		String rightStrand = rightChild.print(path);
		Files.write(path.resolve(leftStrand + "-" + rightStrand + ".csv"),
			printOut, Charset.forName("US-ASCII"));
		return leftStrand + "," + rightStrand;
	}
}
